package com.example.forum.services.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.MessageMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Message;
import com.example.forum.model.User;
import com.example.forum.services.IMessageService;
import com.example.forum.services.IUserServices;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * date: 2024/09/19 15:40<br/>
 * Description:站内信
 *
 * @author: jmy <br/>
 */

@Service
@Slf4j
public class MessageServiceImpl implements IMessageService {
    @Resource
    private MessageMapper messageMapper;
    @Resource
    private IUserServices userServices;

    @Override
    public void create(Message message) {

        //1.非空校验
        if (message == null ||
                message.getPostUserId() == null ||
                message.getReceiveUserId() == null ||
                "".equals(message.getContent())) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
            log.error(e.getStackTrace().toString());
            throw e;
        }


        //3.设置 消息的默认值 0未读 1 2
        message.setDeleteState((byte) 0);//删除状态
        message.setCreateTime(new Date());//创建时间
        message.setUpdateTime(new Date());//跟新时间
        message.setState((byte) 0);//消息状态 未读

        //4.调用mapper
        int row = messageMapper.insert(message);

        //5.判断是否插入成功
        if (row == 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED));
            log.error(e.getStackTrace().toString());
            throw e;
        }
        return;
    }

    @Override
    public int selectUnreadCount(Long receiveUserId) {
        //非空校验
        if (receiveUserId == null || receiveUserId <= 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
            log.error(e.getMessage());
            throw e;
        }
        //调用mapper
        Integer row = messageMapper.selectUnreadCount(receiveUserId);
        if (row == 0) {
            return 0;
        } else return row;
    }

    @Override
    public List<Message> selectByReceiveUserId(Long receiveUserId) {
        //非空校验
        if (receiveUserId == null || receiveUserId <= 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
            log.error(e.getMessage());
            throw e;
        }

        //调用mapper 查询
        List<Message> messages = messageMapper.selectByReceiveUserId(receiveUserId);
        return messages;
    }

    @Override
    public Message selectById(Long id) {
        //非空校验
        if (id == null || id <= 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
            log.error(e.getMessage());
            throw e;
        }
        //调用mapper
        Message message = messageMapper.selectByPrimaryKey(id);
        return message;
    }

    @Override
    public int updateStateById(Long id, Byte state) {
        //非空校验
        if (id == null || id < 0 ||
                state == null || state < 0 || state > 2) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
            log.error(e.getMessage());
            throw e;
        }

        //构造一个跟新对象
        Message updateMessage = new Message();
        updateMessage.setId(id);
        updateMessage.setState(state);
        updateMessage.setUpdateTime(new Date());

        //调用mapper
        int row = messageMapper.updateByPrimaryKeySelective(updateMessage);

        //返回结果
        if (row != 1) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        return row;
    }

    @Override
    public void reply(Long repliedId, Message message) {
        //参数校验
        if (repliedId == null || repliedId < 0) {
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验repliedId 对应的站内信状态
        Message existsMessage = messageMapper.selectByPrimaryKey(repliedId);
        if (existsMessage == null || existsMessage.getDeleteState() == 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS));
        }
        // 获取 回复人&发送人 信息，校验 回复人和 发送人状态
        User receiveUser = userServices.selectById(message.getReceiveUserId());
        User postUser = userServices.selectById(message.getPostUserId());
        if (postUser.getDeleteState() == 1 ||
                receiveUser.getDeleteState() == 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        if (postUser.getState() == 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }

        //回复内容写入数据库
        Date time = new Date();
        message.setUpdateTime(time);
        message.setCreateTime(time);
        create(message);
        //修改被回复消息的状态
        updateStateById(repliedId, (byte) 2);
    }
}
